package cn.ujn.edu.sun_shine.controller;


import cn.ujn.edu.sun_shine.entity.SysUser;
import cn.ujn.edu.sun_shine.service.SysUserService;
import cn.ujn.edu.sun_shine.util.MD5Encoder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 徐冠宇 DoDo
 * @since 2020-11-06
 */
@Controller
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @RequestMapping("/login")
    public String login(@RequestParam("usercode") String usercode, @RequestParam("password") String password, Model model, HttpSession session) throws UnsupportedEncodingException, NoSuchAlgorithmException {
// 通过账号和密码查询用户
        String pass=MD5Encoder.geMd5(password);
        SysUser user = sysUserService.getOne(new QueryWrapper<SysUser>().eq("user_state", 1).eq("user_code", usercode).eq("user_password", pass));
        if(user != null){
            // 将用户对象添加到Session
            session.setAttribute("USER_SESSION", user);
            // 跳转到主页面
			return "redirect:/customer/index";

        }
        model.addAttribute("msg", "账号或密码错误，请重新输入！");
        // 返回到登录页面
        return "login";
    }
    @RequestMapping("/loginout")
    public String loginout(HttpSession session){
        session.invalidate();
        // 重定向到登录页面的跳转方法
        return "redirect:index";

    }
}
